<?php
declare(strict_types = 1);

namespace  plugin\banmitongcheng\api;


use app\banmi\common\Basehome;
use think\facade\Db;
use app\api\service\UploadService;
use think\exception\ValidateException;
use think\facade\Validate;
use think\facade\Log;
use think\facade\Filesystem;
use app\banmi\dispatch\UserDispatch;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;

class Index extends Basehome
{
    
    public $NotLogin= ["set_find","shop_search","index" ,"shop_list","ViewAjax"];
 
  
// 过滤掉emoji表情
    public function filterEmoji($str)
    {
        $str = preg_replace_callback(
        '/./u',
        function (array $match) {
            return strlen($match[0]) >= 4 ? '' : $match[0];
        },
        $str
    );
        return $str;
    }
    
    
    
    public function set_find()
    {
        $find =  Db::name('plugin_banmitongcheng_set')->where('id', 1)->find();
        $data['find']= $find;
        ajaxmsg('ok', 200, $data);
    }
    
 
    public function shop_search()
    {
        $arr = $_POST;
        $paginate=20;
        $lat=  input('request.lat', '');//39.897528
        $lng=  input('request.lng', '');//116.330742
        $keyword=  input('request.keyword', '');
        if (!$keyword) {
            ajaxmsg('请输入关键词', 0);
        }
        $where[] = ['status', '=', 2];
   
        $where[] = ['shop_name', 'like', "%{$keyword}%"];
 
        
        $shoplist =  Db::name('plugin_banmitongcheng_shop_list')->where($where)->paginate($paginate);
 
      
        $shoplist = $shoplist->all();
        foreach ($shoplist as $key => $value) {
            $shoplist[$key]['tag'] = explode(',', $value['shop_tag']);
            $shoplist[$key]['distance'] = ajaxposition($lat, $lng, $value['shop_lng'], $value['shop_lat']);
        }
        
        
        $data['shop_list']= $shoplist;
        ajaxmsg('ok', 200, $data);
    }
  
    
    public function Shop_my_shop_del()
    {
        $uid = is_login();
        $id=input('request.id');
        $map['id']=$id;
        $map['uid']=$uid;
        Db::name('plugin_banmitongcheng_shop_list')->where($map)->update(['status' => '-1' ]);
            
        ajaxmsg('删除成功', 200);
    }
    public function Shop_my_shop()
    {
        $arr = $_POST;
        $uid = is_login();
        $paginate=20;
        $lat=  input('request.lat', '');//39.897528
        $lng=  input('request.lng', '');//116.330742
        $map['uid']=$uid;
        $shoplist =  Db::name('plugin_banmitongcheng_shop_list')->where($map)->where('status', '>=', '0')->paginate($paginate);
 
    
        $shoplist = $shoplist->all();
        
        // $find =  Db::name('plugin_banmitongcheng_set')->where('id',1)->find();
        
        foreach ($shoplist as $key => $value) {
            $shoplist[$key]['tag'] = explode(',', $value['shop_tag']);
            $shoplist[$key]['distance'] = ajaxposition($lat, $lng, $value['shop_lng'], $value['shop_lat']);
        }
        
     
        $data['list']= $shoplist;
        ajaxmsg('ok', 200, $data);
    }
    public function Shop_my_collection_del()
    {
        $uid = is_login();
        $id=input('request.id');
        $map['id']=$id;
        $map['uid']=$uid;
        Db::name('plugin_banmitongcheng_shop_collection')->where($map)->delete();
        ajaxmsg('删除成功', 200);
    }
    public function Shop_my_collection()
    {
        $arr = $_POST;
        $uid = is_login();
        $paginate=20;
        $lat=  input('request.lat', '');//39.897528
        $lng=  input('request.lng', '');//116.330742
        
        $map['a.uid']=$uid;
        $map['b.status']=2;
        $shoplist =  Db::name('plugin_banmitongcheng_shop_collection')->alias('a')
                ->join('plugin_banmitongcheng_shop_list b', 'a.shop_id = b.id')
        
        ->where($map)->field('a.id,b.shop_name,b.shop_img,b.shop_tel,b.shop_addr,b.shop_lng,b.shop_lat,b.business_time,b.uid,b.shop_tag')->paginate($paginate);
    
 
        $shoplist = $shoplist->all();
        foreach ($shoplist as $key => $value) {
            $shoplist[$key]['tag'] = explode(',', $value['shop_tag']);
            $shoplist[$key]['distance'] = ajaxposition($lat, $lng, $value['shop_lng'], $value['shop_lat']);
        }
        
        
        $data['list']= $shoplist;
        ajaxmsg('ok', 200, $data);
    }
  
    
    public function ShopAddajax()
    {
        $arr = $_POST;
        $uid = is_login();
 
 

        if (empty($arr['shop_name'])) {
            ajaxmsg('请输入店铺名称', 0);
        }
        if (empty($arr['shop_tel'])) {
            $result['msg'] = '请输入联系电话！';
            ajaxmsg($result['msg'], 0);
        }
 
        if (empty($arr['shop_tag'])) {
            $result['msg'] = '请输入商家标签！';
            ajaxmsg($result['msg'], 0);
        }
        if (empty($arr['shop_lng'])) {
            $result['msg'] = '请选择商家地址！';
            ajaxmsg($result['msg'], 0);
        }
        if (empty($arr['business_time'])) {
            $result['msg'] = '请选择营业时间！';
            ajaxmsg($result['msg'], 0);
        }
    
        if (empty($arr['nav_id'])) {
            $result['msg'] = '请选择店铺分类！';
            ajaxmsg($result['msg'], 0);
        }
        if (empty($arr['shop_img'])) {
            $result['msg'] = '请上传店铺头像！';
            ajaxmsg($result['msg'], 0);
        }
        $arr['shop_tag'] = str_replace("，", ",", $arr['shop_tag']);
        
 
        $set_json = plugin_config(0);
       
        $status=$set_json['is_check_examine'];
 
        $shop_data = array(
            'shop_name' => $arr['shop_name'],
            'shop_img'  => $arr['shop_img'],
            'shop_tel'  => $arr['shop_tel'],
            'shop_tag'  => $arr['shop_tag'],
            'shop_addr' => $arr['shop_addr'],
            'business_time' => $arr['business_time'],
            'creation_time' => time(),
            'creation_ip' => request()->ip(),
            'uid' => $uid,
            'nav_id' => $arr['nav_id'],
            'shop_lng' => $arr['shop_lng'],
            'shop_lat' => $arr['shop_lat'],
            'status' =>$status
            );
        
        $shop_find =  Db::name('plugin_banmitongcheng_shop_list')->where('uid', $uid)
           ->where('status', '>=', '0')->find();
        
        if (!empty($shop_find)) {
            //   if ($status_set['is_check_pay']==1&&time()>$shop_find['vip_end_time']) {//已开启了付费模式
            //                   ajaxmsg('会员已到期，无法编辑，请付费' , 101);
            //     }
            Db::name('plugin_banmitongcheng_shop_list')->where('id', $shop_find['id'])->data($shop_data)->update();
            ajaxmsg('编辑成功', 200);
        }
        $shop_data['vip_end_time']=time();
        $result =  Db::name('plugin_banmitongcheng_shop_list')->insertGetId($shop_data);
        if (!empty($result)) {
            $this->update_statistics();
             
             
            $platform =  input('request.banmi_platform');
      
            if ($platform=='MP-WEIXIN') {
                $this->code_ma($result);
            }
            ajaxmsg('恭喜入住成功！等待跳转', 200, $result);
        }
        
        ajaxmsg('入住失败！', 0);
    }
    
    
    
    
    public static function update_statistics()
    {
        $map['t_id'] =1;
        $find =Db::name('plugin_banmitongcheng_statistics')->where($map)->find();
        if ($find) {
            Db::name('plugin_banmitongcheng_statistics')->where($map)->inc('shop_num')->update();
        } else {
            $data = ['t_id' => 1, 'shop_read' => 1  , 'shop_num' => 1 ];
            Db::name('plugin_banmitongcheng_statistics')->insert($data);
        }
    }
    
    
    public function shop_edit()
    {
        $uid = is_login();
    
        $NavList = Db::name('plugin_banmitongcheng_shop_nav')->where('type', 0)->select();
        $find =  Db::name('plugin_banmitongcheng_shop_list')->where('status', '>=', '0')->where('uid', $uid)->find();
        $data['NavList'] = $NavList;
        $data['find'] = $find;
 
        ajaxmsg('ok', 200, $data);
    }
    
    public function index()
    {
        $statistics = Db::name('plugin_banmitongcheng_statistics')->where('t_id', 1)->find();
        $NavList = Db::name('plugin_banmitongcheng_shop_nav')->order('sort asc')->select();
        $NavList = $NavList->all();
        
        $shop_num =  Db::name('plugin_banmitongcheng_shop_list')->where('status', 2)->count();
        $data['shop_num'] = $shop_num;
        $data['statistics'] = $statistics;
        $data['NavList'] = $NavList;
        ajaxmsg('ok', 200, $data);
    }

    public function shop_list()
    {
        $nav_id =    input('request.nav_id');
        $keyword =   input('request.keyword');
        $tabindex =  input('request.tabindex', 1);
        $lat=  input('request.lat');//39.897528
        $lng=  input('request.lng');//116.330742

        $paginate=20;
        $field = 'id';
        if ($tabindex == 0) {
            $field = 'top_end_time';
        } elseif ($tabindex == 2) {
            $field = 'id';
        }
        $page = 1;
        $map['status']=2;
        $where = "status=2";
        $NavList = Db::name('plugin_banmitongcheng_shop_nav')->select();
        $data['NavList']=$NavList;
        
      
        if ($nav_id > 0) {
            $map['nav_id']=$nav_id;
            $where.= " and nav_id= " . $nav_id;
        }
        if (!empty($keyword)) {
            $where.= " and shop_name like '%{$keyword}%'";
        }
      
        if ($tabindex == 1) {
            if (empty($lat)) {
                $data['shop_list']=[];
                ajaxmsg('ok', 200, $data);
            }
            $shoplist=  $this->getDistanceByLatLng('app_plugin_banmitongcheng_shop_list', $lat, $lng, $paginate, $map);
        } else {
            $shoplist=  Db::name('plugin_banmitongcheng_shop_list')->where($map) ->order($field.' desc')->paginate($paginate);
        }
    
       
        $shoplist = $shoplist->all();
        foreach ($shoplist as $key => $value) {
            $shoplist[$key]['tag'] = explode(',', $value['shop_tag']);
            $shoplist[$key]['distance'] = ajaxposition($lat, $lng, $value['shop_lng'], $value['shop_lat']);
        }
        $data['shop_list']=$shoplist;
        ajaxmsg('ok', 200, $data);
    }
    
    public function ViewAjax()
    {
        $id =  input('request.id');
        $find =  Db::name('plugin_banmitongcheng_shop_list')->where('id', $id)->where('status', 2)->find();
        
        if (empty($find)) {
            ajaxmsg('商家不存在,或审核中', 0);
        }
        $find['is_collection'] = 0;
        $uid = is_login(1);
      
      
 
           

        if ($uid) {
            $is_find =   Db::name('plugin_banmitongcheng_shop_collection')->where(['shop_id'=>$find['id'],'uid'=>$uid])->find();
            if ($is_find) {
                $find['is_collection'] = 1;
            }
        }
        $this->update_statistics();
        $platform =  input('request.banmi_platform');
        $wx_code_img =0 ;
        if ($platform=='MP-WEIXIN') {
            $wx_code_img=   $this->code_ma($find['id']);
        }
        
     
        
        $find['ma_img']=home_url().'/attachment/storage/files/bantongchengshop/'.$id.'.png';
        $data['find'] = $find;
        $data['wx_code_img'] = $wx_code_img;
        ajaxmsg('ok', 200, $data);
    }
    
    public function Shop_collection_add()
    {
        $uid = is_login();
        $shop_id = input('request.shop_id');
        if (empty($shop_id)) {
            ajaxmsg('非法操作', 0);
        }
        $map['uid']=$uid;
        $map['shop_id']=$shop_id;
        $is_find =  Db::name('plugin_banmitongcheng_shop_collection')->where($map)->find();
        
        if (!empty($is_find)) {
            $is_del =   Db::name('plugin_banmitongcheng_shop_collection')->delete($is_find['id']);
            ajaxmsg('已取消收藏', 100);
        }
        $result =  Db::name('plugin_banmitongcheng_shop_collection')->insert([
            'uid' => $uid,
            'shop_id' => $shop_id ,
            'creation_time' => time() ,
            ]);
        ajaxmsg('收藏成功', 200);
    }
    
    

    
    public function getDistanceByLatLng($database_name, $lat, $lng, $paginate, $map)
    {
        $order = 'asc';
        $field_lat = 'shop_lat';
        $field_lng = 'shop_lng';
        return Db::table($database_name)
      ->field("*, (6378.138 * 2 * asin(sqrt(pow(sin(({$field_lat} * pi() / 180 - {$lat} * pi() / 180) / 2),2) + cos({$field_lat} * pi() / 180) * cos({$lat} * pi() / 180) * pow(sin(({$field_lng} * pi() / 180 - {$lng} * pi() / 180) / 2),2))) * 1000) as distance")
       ->where($map)
      ->order("distance {$order}")
      ->paginate($paginate);
    }

    private function code_ma($id)
    {
        $find = plugin_config();
 
        $appid = $find['wx_appid'];
        $secret = $find['wx_secret'];
       
        if (!$appid) {
            return 0;
        }
        if (!$secret) {
            return 0;
        }
        $id=intval($id);
        $mulu_pl='bantongchengshop';
        $mulu=root_path() . 'bmapp/attachment/storage/files/'.$mulu_pl.'/';
        $this->cj_mulu($mulu);
        $img = $mulu . $id.'.png';
        if (is_file($img)) {
            return 200;
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;
 
        $access_token_data = $this->getJson($url);
      
        $access_token = $access_token_data['access_token'];
        if (!empty($access_token)) {
            $url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token=' . $access_token;
            $data['path'] = 'pages/ban_tongchengshop/shop_view?id='.$id.'&query=1';
            $data['width'] = 100;
            $result = $this->curlPost($url, $data, 'POST');
         
            $ret = file_put_contents($img, $result);
        }
    }
    private function getJson($url, $data = array(), $method = 'GET')
    {
        $ch = curl_init(); //1.初始化
        curl_setopt($ch, CURLOPT_URL, $url); //2.请求地址
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //3.请求方式
        //4.参数如下
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if ($method == "POST") { //5.post方式的时候添加数据
            $data = json_encode($data);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }
    private function curlPost($url, $data, $method)
    { 
        $ch = curl_init(); //1.初始化
        curl_setopt($ch, CURLOPT_URL, $url); //2.请求地址
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //3.请求方式
        //4.参数如下
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //https
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)'); //模拟浏览器
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept-Encoding: gzip, deflate')); //gzip解压内容
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
        if ($method == "POST") { //5.post方式的时候添加数据
            $data = json_encode($data);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch); //6.执行
        if (curl_errno($ch)) { //7.如果出错
            return curl_error($ch);
        }
        curl_close($ch); //8.关闭
        return $tmpInfo;
    }
    //创建目录
    private function cj_mulu($path)
    {
        
        //判断目录存在否，存在给出提示，不存在则创建目录
        if (is_dir($path)) {
            return 0;
        } else {
            //第三个参数是“true”表示能创建多级目录，iconv防止中文目录乱码
            $res=mkdir(iconv("UTF-8", "GBK", $path), 0777, true);
            if ($res) {
                return 200;
            }
            return 1;
        }
    }
}
